package com.alibaba.dingtalk.openapi.demo;
import java.io.BufferedReader;  
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;  
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;  
  
import org.apache.http.HttpResponse;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.mime.HttpMultipartMode;  
import org.apache.http.entity.mime.MultipartEntity;  
import org.apache.http.entity.mime.content.FileBody;  
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.dingtalk.openapi.demo.utils.HttpHelper;  
  
public class Upload {  
    @SuppressWarnings("deprecation")
	public static void main(String args[]) throws Exception {  
          
        @SuppressWarnings("deprecation")
		MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"----------ThIs_Is_tHe_bouNdaRY_$", Charset.defaultCharset());     
        File file=new File(System.getProperty("user.dir")+"/src/test/test.jpg");
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = null;
        fc = fis.getChannel();
        long FILE_SIZE=fc.size();
        multipartEntity.addPart("image",new FileBody(file,"jpg/png"));    
            
        HttpPost request = new HttpPost("https://oapi.dingtalk.com/file/upload/single?access_token=9755c61745c132f486464cda975c8e19&agent_id=102769385&file_size="+FILE_SIZE);     
        request.setEntity(multipartEntity);  
        request.addHeader("Content-Type","multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$");  
          
        CloseableHttpClient httpClient = HttpClients.createDefault(); 
        HttpResponse response =httpClient.execute(request);  
          
        InputStream is = response.getEntity().getContent();  
        BufferedReader in = new BufferedReader(new InputStreamReader(is));  
        StringBuffer buffer = new StringBuffer();  
        String line = "";  
        while ((line = in.readLine()) != null) {  
            buffer.append(line);  
        }  
        System.out.println(FILE_SIZE);
        System.out.println("发送消息收到的返回："+buffer.toString());  
      
    }  
}  